/*************************************************************************
	> File Name: once.c
	> Author: 
	> Mail: 
	> Created Time: 2015年01月14日 星期三 10时06分36秒
 ************************************************************************/
#include <pthread.h>
#include "errors.h"

pthread_once_t once_block = PTHREAD_ONCE_INIT;
pthread_mutex_t mutex;

void once_init_routine(void){
    int status;

    status = pthread_mutex_init(&mutex,NULL);
    if(status) err_abort(status,"Init mutex");

    printf("once_init_routine is run \n");
}
// thread start routine that calls pthread_once

void *thread_routine(void *arg){
    int status;

    status = pthread_once(&once_block,once_init_routine);
    if(status) err_abort(status,"Once init");

    status = pthread_mutex_lock(&mutex);
    if(status)  err_abort(status,"Lock mutex");
    printf("thread_routine has locked the mutex\n");

    status = pthread_mutex_unlock(&mutex);
    if(status)  err_abort(status,"Unlock mutex");
    printf("thread_routine has unlocked the mutex\n");

    return NULL;
}


int main(int argc,char *argv[]){
    pthread_t thread_id;
    char * input, buffer[64];

    int status;

    status = pthread_create(&thread_id,NULL,thread_routine,NULL);
    if(status) err_abort(status,"create pthread");

    status = pthread_once(&once_block,once_init_routine);
    if(status) err_abort(status,"Once init");

    status = pthread_mutex_lock(&mutex);
    if(status) err_abort(status,"lock mutex");

    printf("main thread lock the mutex\n");

    status = pthread_mutex_unlock(&mutex);
    if(status) err_abort(status,"unlock mutex");
    printf("main thread ulock the mutex\n");

    status = pthread_join(thread_id,NULL);
    if(status) err_abort(status,"Join thread");
    return 0;
}

